import {pool} from './db.js'


export async function getConfig(host_name) {
    let connection;
    try {
        connection = await pool.promise().getConnection();
        const results = await connection.query('SELECT xunfei_api_key, xunfei_api_secret, api_key FROM app_configs WHERE host_name = ? limit 1', host_name);
        if (results.length == 0) {
            throw new Error(`host ${host_name} api config not exist`)
        }        
        return results[0][0]
    } catch (err) {
        console.log('[QUERY ERROR] - ', err.message);
        throw err
    } finally {
        if (connection) {
            connection.release();
        }
    }
}


export async function saveDocTitle(title, account) {
    let connection;
    try {
        connection = await pool.promise().getConnection();
        await connection.query('Insert into doc_titles (title, account, created_at) values (?, ?, ?) ', [title, account, new Date()]);
    } catch (err) {
        console.log(`[save ${title} of ${account} ERROR] - ${err.message}`);
        throw err
    } finally {
        if (connection) {
            connection.release();
        }
    }
}



export async function removeDocTitle(title) {
    let connection;
    try {
        connection = await pool.promise().getConnection();
        await connection.query('DELETE FROM doc_titles WHERE title = ?', title);
    } catch (err) {
        console.log(`[remove ${title}  ERROR] - ${err.message}`);
        throw err
    } finally {
        if (connection) {
            connection.release();
        }
    }
}



